/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


package search;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopScoreDocCollector;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.LockObtainFailedException;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.Version;
import org.apache.lucene.store.FSDirectory;
import java.io.File;
import java.sql.*;
/**
 *
 * @author Yasmani
 */

public class Searchproduct implements Runnable{
    
    private static final String URL = "jdbc:mysql://localhost:3306/ismi";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "csi518";
    private Connection connection = null;
    private PreparedStatement select = null;
    private ResultSet rst = null;
    private String[] fields = {"name", "description"};
    private String s;
    
    public Searchproduct(String s){
        this.s = s;
    }
    

    public void run()
            
    {
        String indexPath = "/resources/index";
        try {
            
            
            Class.forName("com.mysql.jdbc.Driver");
            
            connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
            
            select = connection.prepareStatement("SELECT product_id, product_name, product_description,"
                    +"user_name FROM product");
            
            rst = select.executeQuery();
            
            
            
            
            StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_35);

         // 1. create the index
            
            
         Directory index = FSDirectory.open(new File(indexPath));

         IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_35, analyzer);
         config.setOpenMode(IndexWriterConfig.OpenMode.CREATE);

         IndexWriter w = new IndexWriter(index, config);
         
         while(rst.next()){
                    addDoc(w, rst.getString("product_id"), rst.getString("product_name"), 
                            rst.getString("product_description"), rst.getString("user_name"));
         }
         
         w.close();
         

         // 2. query
         

         // the "title" arg specifies the default field to use
         // when no field is explicitly specified in the query.
         Query q = new MultiFieldQueryParser(Version.LUCENE_35, fields, analyzer).parse(s);

         // 3. search
         int hitsPerPage = 10;
         IndexReader reader = IndexReader.open(index);
         IndexSearcher searcher = new IndexSearcher(reader);
         TopScoreDocCollector collector = TopScoreDocCollector.create(hitsPerPage, true);
         searcher.search(q, collector);
         ScoreDoc[] hits = collector.topDocs().scoreDocs;
         
         // 4. display results
         System.out.println("Found " + hits.length + " hits.");
         for(int i=0;i<hits.length;++i) {
           int docId = hits[i].doc;
           Document d = searcher.doc(docId);
           
           
           System.out.println((i + 1) + ". " + d.get("id")+" "+ d.get("name")
                   +"\n"+ d.get("description")+" "+ d.get("user"));
         }

         // searcher can only be closed when there
         // is no need to access the documents any more. 
         //w.close();
         searcher.close();
        } catch (CorruptIndexException ex) {
            Logger.getLogger(Searchproduct.class.getName()).log(Level.SEVERE, null, ex);
        } catch (LockObtainFailedException ex) {
            Logger.getLogger(Searchproduct.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Searchproduct.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParseException ex) {
            Logger.getLogger(Searchproduct.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(Searchproduct.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Searchproduct.class.getName()).log(Level.SEVERE, null, ex);
        }
        finally {            
            try{
                if(connection != null)
                    connection.close();
                if(rst != null)
                    rst.close();
            }
            catch (SQLException ex) {
            Logger.getLogger(Searchproduct.class.getName()).log(Level.SEVERE, null, ex);
        }
        }
  } 
        
   private static void addDoc(IndexWriter w, String id, String name, String desc, String user) throws IOException, SQLException {
    Document doc = new Document();
    doc.add(new Field("id", id, Field.Store.YES, Field.Index.NO));
    doc.add(new Field("user", user, Field.Store.YES, Field.Index.NO));
    doc.add(new Field("name", name, Field.Store.YES, Field.Index.ANALYZED));
    doc.add(new Field("description", desc, Field.Store.YES, Field.Index.ANALYZED));
    w.addDocument(doc);
    
  }    
        
    }

